let _Vue = null;

class MyRouter {
  static install(Vue) {
    if (MyRouter.install.installed) return;
    MyRouter.install.installed = true;

    _Vue = Vue;
    Vue.mixin({
      beforeCreate() {
        console.log(this.$router?.data?.current);
        if (this.$options.router) {
          Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        }
      }
    })
  }

  constructor(options) {
    this.options = options;
    this.routeMap = new Map();
    this.data = _Vue.observable({
      current: '/'
    })
  }

  init() {
    this.createRouteMap();
    this.initEvent();
    this.initComponent();
  }

  createRouteMap() {
    this.options.routes.forEach(route => {
      this.routeMap.set(route.path, route.component);
    })
  }

  initEvent() {
    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname;
    })
  }

  initComponent() {
    this.addRouterView();
    this.addRouterLink();
  }

  addRouterView() {
    _Vue.component('router-view', {
      name: 'RouterView',
      render(h) {
        const cur = this.$router.routeMap.get(this.$router.data.current)
        return h(cur);
      }
    });

  }

  addRouterLink() {
    _Vue.component('router-link', {
      name: 'RouterLink',
      props: ['to'],
      template: `<a :href="to" @click="handler"><slot></slot></a>`,
      methods: {
        handler(e) {
          history.pushState({}, '', this.to);
          this.$router.data.current = this.to;
          e.preventDefault();
        }
      }
    });
  }
}